package beautiful.butterfly.server.httpserver.mvc.core;

import beautiful.butterfly.server.httpserver.mvc.aop.InterceptorsAndActionExecute;
import beautiful.butterfly.server.httpserver.mvc.http.Request;
import beautiful.butterfly.server.httpserver.mvc.render.Render;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public final class ActionExecute {

    private static final String Index_Url = "/";
    private static final String Index_Url_To_Action_Url = "/index/index.html";
    private static Logger logger = LoggerFactory.getLogger(ActionExecute.class);


    // 加载配置文件
    public ActionExecute() {
        ActionMapping.buildActionMapping();

    }

    /**
     * 只接受.html的请求
     */
    public Render execute(Request request) throws IOException {
        String key = request.getUri();
        if (Index_Url.equals(key)) {// /
            key = Index_Url_To_Action_Url;
        }
        int index = key.lastIndexOf(".html");
        if (index != -1) {
            key = key.substring(0, index);
        }
        Action action = ActionMapping.getAction(key);
        if (action == null) {
            return null;
        } else {
            Controller controller = action.getController();
            ActionReporter.doReport(controller, action);
            return (new InterceptorsAndActionExecute(action, controller)).invoke();

        }

    }

}
